package com.lance.answer.gui.answer.gk.answer.lms.batch.task;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.alibaba.fastjson.serializer.SerializerFeature;
import com.google.common.base.Strings;
import com.google.common.collect.Lists;
import com.google.common.collect.Maps;
import com.lance.answer.dto.CompleteInfo;
import com.lance.answer.gui.answer.Util;
import com.lance.answer.gui.answer.gk.answer.lms.Courseware;
import com.lance.answer.gui.answer.gk.answer.lms.batch.dto.LmsWatchDTO;
import com.lance.answer.gui.answer.gk.answer.lms.dto.LmsActivities;
import com.lance.answer.gui.answer.gk.answer.lms.dto.LmsCompleteness;
import com.lance.answer.gui.answer.gk.answer.lms.dto.LmsModule;
import com.lance.answer.gui.answer.gk.answer.lms.util.LmsUtil;
import com.lance.answer.gui.answer.gk.video.dto.WatchVideoDto;
import com.lance.answer.util.HttpUtil;
import lombok.SneakyThrows;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.io.FileUtils;
import org.apache.commons.io.IOUtils;
import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.chrome.ChromeDriver;
import org.openqa.selenium.support.ui.ExpectedCondition;
import org.openqa.selenium.support.ui.WebDriverWait;

import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.nio.charset.StandardCharsets;
import java.time.Duration;
import java.util.List;
import java.util.Map;
import java.util.concurrent.LinkedBlockingDeque;
import java.util.concurrent.TimeUnit;

/**
 * <p>拿到所有课程的链接 2022-4-30<p>
 * <p>
 * <p>4-28 FIXME 课程讨论区的的帖子的ID还没获取到？？？？？？？？？？？？？？？？？？
 * <p>
 * <p>
 * 工程经济,size:1
 *
 * @author : fengx
 * @since JDK8.0
 * create by fengx on 2022/4/19 14:47
 */
@Slf4j
public class LmsSaveUnVideoTask extends Thread {


    private final String driverPath;
    private final LinkedBlockingDeque<LmsWatchDTO> watchDTOS;

    public LmsSaveUnVideoTask(String driverPath, LinkedBlockingDeque<LmsWatchDTO> watchDTOS) {
        this.driverPath = driverPath;
        this.watchDTOS = watchDTOS;
    }

    @SneakyThrows
    @Override
    public void run() {

        while (watchDTOS.size() > 0) {
            LmsWatchDTO lmsWatchDTO = watchDTOS.take();
            String userName = lmsWatchDTO.getUsername();
            String password = lmsWatchDTO.getPassword();
            log.info("任务：{} 剩余 {} 行 用户名：{} 密码：{}",
                    Thread.currentThread().getName(), watchDTOS.size(), userName, password);
            System.err.println("执行任务11111");
            run(driverPath, lmsWatchDTO);
        }

        if (watchDTOS.size() == 0) {
            log.info("课程所有用户均已执行完毕，系统将在20min后结束");
            TimeUnit.MINUTES.sleep(20);
            return;
        }
    }


    public static void run(String driverPath, LmsWatchDTO lmsWatchDTO) throws Exception {

        ChromeDriver driver = Util.getDriver(driverPath);
        String url = "https://menhu.pt.ouchn.cn/site/ouchnPc/index";
        driver.get(url);
        Thread.sleep(3000);


        String userName = lmsWatchDTO.getUsername();
        String pwd = lmsWatchDTO.getPassword();

        LmsUtil.login(driver,userName,pwd);

        Map<Long, String> courseMap = lmsWatchDTO.getCourseMap();


        Util.switchToFirst(driver);

        if (courseMap == null) {
            return;
        }
        for (Long courseId : courseMap.keySet()) {
          try{
              study(driver, courseId);
          }catch (Exception e){

          }
        }

    }


    public static LmsModule getUserModules(WebDriver driver, Long courseId) {

        LmsModule lmsModule = null;
        try {
            String getModules = "https://lms.ouchn.cn/api/courses/" + courseId + "/modules";
            String cookie = Util.getCookie(driver.manage().getCookies());
            Map<String, String> heads = Maps.newHashMap();
            heads.put("referer", "https://lms.ouchn.cn/course/" + courseId + "/ng");
            heads.put(":method", "GET");
            heads.put(":authority", "lms.ouchn.cn");
            heads.put("cookie", cookie);
            heads.put(":path", "/api/courses/" + courseId + "/modules");
            heads.put("accept", "application/json, text/plain, */*");
            lmsModule = JSON.parseObject(HttpUtil.get(getModules, cookie, heads), LmsModule.class);
        } catch (Exception e) {

        }
        return lmsModule;
    }

    public static LmsActivities getUserActivities(WebDriver driver, Long courseId, List<Long> moduleIdList) {

        LmsActivities lmsActivities = null;
        try {
            String getModules = "https://lms.ouchn.cn/api/course/" + courseId + "/all-activities" +
                    //   "?module_ids=[40000007098]" +
                    "?module_ids=" + JSON.toJSONString(moduleIdList) +
                    "&activity_types=learning_activities,exams,classrooms,live_records,rollcalls" +
                    "&no-loading-animation=true";
            String cookie = Util.getCookie(driver.manage().getCookies());
            Map<String, String> heads = Maps.newHashMap();
            heads.put("referer", "https://lms.ouchn.cn/course/" + courseId + "/ng");
            heads.put(":method", "GET");
            heads.put(":authority", "lms.ouchn.cn");
            heads.put("cookie", cookie);
            heads.put(":path", "/api/course/" + courseId + "/all-activities" +
                    //   "?module_ids=[40000007098]" +
                    "?module_ids=" + JSON.toJSONString(moduleIdList) +
                    "&activity_types=learning_activities,exams,classrooms,live_records,rollcalls&no-loading-animation=true");
            heads.put("accept", "application/json, text/plain, */*");
            lmsActivities = JSON.parseObject(HttpUtil.get(getModules, cookie, heads), LmsActivities.class);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return lmsActivities;
    }


    public static void study(WebDriver driver, Long courseId) throws InterruptedException {

        driver.get("https://lms.ouchn.cn/course/" + courseId + "/ng#/");


        Thread.sleep(5000);

        LmsModule lmsModule = getUserModules(driver, courseId);
        if (null == lmsModule) {
            log.info("courseId:{}获取章节模块为空", courseId);
            return;
        }

        List<Long> moduleIdList = Lists.newArrayList();
        for (LmsModule.ModulesDTO modulesDTO : lmsModule.getModules()) {
            moduleIdList.add(modulesDTO.getId());
        }

        LmsActivities activities = getUserActivities(driver, courseId, moduleIdList);

        List<Long> videoIdIds = Lists.newArrayList();
        Map<Long, String> videoMap = Maps.newLinkedHashMap();
        for (LmsActivities.LearningActivitiesDTO activitiesDTO : activities.getLearningActivities()) {
            System.err.println("activitiesDTO.getId()" + activitiesDTO.getId() + "   type:" + activitiesDTO.getType());
            //    if(activitiesDTO.getType().equals("video")){
            // FIXME 应该是online_video 现在为了做测试放开！
//           if(activitiesDTO.getType().equals("online_video")){
//               continue;
//           }
            /**
             * FIXME :形考任务的连接好像获取不完全？？？ exam答题的获取不到
             * 初步理解：
             * online_video  视频、音频
             * homework
             * forum 发表帖子
             * material  浏览线上的PDF
             * web_link 超链接
             * page 普通的浏览网页
             */
            videoIdIds.add(activitiesDTO.getId());
            videoMap.put(activitiesDTO.getId(), activitiesDTO.getType());
        }

        //    Thread.sleep(200000000);


        // 已经完成的视频教程
        List<Long> completeLearningActivity = Lists.newArrayList();

        try {
            LmsCompleteness lmsCompleteness = getLmsCompleteness(driver, courseId);
            completeLearningActivity.addAll(lmsCompleteness.getCompletedResult().getCompleted().getLearningActivity());
        } catch (Exception e) {
            e.printStackTrace();
        }


        for (Map.Entry<Long, String> entry : videoMap.entrySet()) {
            long videoId = entry.getKey();
            String videoType = entry.getValue();

            if (completeLearningActivity.contains(videoId)) {
                continue;
            }

            try {
                // https://lms.ouchn.cn/course/40000000852/learning-activity/full-screen#/40000261482
                driver.get("https://lms.ouchn.cn/course/" + courseId + "/learning-activity/full-screen#/" + videoId);
                Thread.sleep(2 * 1000);
                // 需要刷新一下
                driver.navigate().refresh();
                Thread.sleep(5 * 1000);
                if ("page".equals(videoType)) {
                    savePageInfo(driver, courseId, videoId);
                }
                if ("forum".equals(videoType)) {
                    createTopic(driver);
                }
                if ("material".equals(videoType)) {

                    scanPagePdf(driver);
                }
                if ("web_link".equals(videoType)) {
                    clickHref(driver);
                }
                if ("online_video".equals(videoType)) {
                    // 因为观看视频要获取更多的信息，比如视频的长度、步长等，这里就不观看视频了。
                    continue;
                }

            } catch (Exception e) {
                e.printStackTrace();
            }
            Thread.sleep(5000);

        }


//        for (Long videoId : videoIdIds) {
//
//           if(completeLearningActivity.contains(videoId)){
//               continue;
//           }
//
//            try {
//                // https://lms.ouchn.cn/course/40000000852/learning-activity/full-screen#/40000261482
//               driver.get("https://lms.ouchn.cn/course/"+courseId+"/learning-activity/full-screen#/"+videoId);
//               Thread.sleep(5*1000);
//
//                savePageInfo(driver,courseId,videoId);
//                Thread.sleep(1000);
//
//               createTopic(driver);
//               Thread.sleep(1000);
//
//               scanPagePdf(driver);
//            } catch (Exception e) {
//                e.printStackTrace();
//            }
//            Thread.sleep(5000);
//
//        }

        System.err.println("end...............");

        //  Thread.sleep(2000000);
    }

    private static void clickHref(WebDriver driver) {
        try {

            WebElement we = driver.findElement(By.cssSelector("a[class='font font-open-link']"));
            if ("新页签打开".equals(Util.dealContent(we.getText()))) {
                we.click();
                Util.switchToLast(driver);
                Thread.sleep(10 * 1000);
                driver.close();
            }


        } catch (Exception e) {

        }
    }

    public static void scanPagePdf(WebDriver driver) {
        try {
            Thread.sleep(2 * 1000);
            WebElement we = Util.findByCssSelector(driver, "span[class='file-name ng-binding']");
        //    Thread.sleep(8 * 1000);
            if (we != null) {
                we.click();
            }
        } catch (Exception e) {

        }
    }

    public static void savePageInfo(WebDriver driver, long courseId, long videoId) {
        String postUrl = "https://lms.ouchn.cn/api/course/activities-read/" + videoId;
        String cookie = Util.getCookie(driver.manage().getCookies());
        Map<String, String> heads = Maps.newHashMap();
        heads.put("referer", "https://lms.ouchn.cn/course/" + courseId + "/learning-activity/full-screen");
        heads.put(":method", "POST");
        heads.put(":authority", "lms.ouchn.cn");
        heads.put("cookie", cookie);
        heads.put(":path", "/api/course/activities-read/" + videoId);
        heads.put("accept", "application/json, text/plain, */*");
        try {
            System.err.println("11111111111:" + HttpUtil.post(postUrl, Maps.newHashMap(), cookie, heads));
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    public static void createTopic(WebDriver driver) {
        try {
            WebElement we = Util.findByCssSelector(driver, "a[data-label=\"发表帖子\"]");
            if (we != null) {
                we.click();
                Thread.sleep(1000);
                driver.findElement(By.cssSelector("input[ng-model='topic.title']")).sendKeys("好好学习，天天向上");
                // driver.findElement(By.cssSelector("textarea[name='content']")).sendKeys("好好学习，天天向上");

                driver.findElement(By.cssSelector("div[class='topic-form-section main-area']")).
                        findElement(By.cssSelector("div[class='simditor']")).click();
                try {
                    driver.findElement(By.id("add-topic-popup")).findElement(By.cssSelector("div[class='simditor-body needsclick']")).sendKeys("好好学习，天天向上");
                } catch (Exception e) {

                }
                for (WebElement saveWe : driver.findElement(By.id("add-topic-popup")).findElements(By.cssSelector("button[class='button button-green medium']"))) {
                    if ("保存".equals(saveWe.getText())) {
                        saveWe.click();
                        break;
                    }
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    public static LmsCompleteness getLmsCompleteness(WebDriver driver, Long courseId) throws Exception {
        String cookie = Util.getCookie(driver.manage().getCookies());
        String getUrl = "https://lms.ouchn.cn/api/course/" + courseId + "/my-completeness";
        Map<String, String> heads = Maps.newHashMap();
        heads.put("referer", "https://lms.ouchn.cn/course/" + courseId + "/ng");
        heads.put(":method", "GET");
        heads.put(":authority", "lms.ouchn.cn");
        heads.put("cookie", cookie);
        heads.put(":path", "/api/course/" + courseId + "/my-completeness");
        heads.put("accept", "application/json, text/plain, */*");

        String result = HttpUtil.getLmsOuchn(getUrl, cookie, heads);
        System.err.println("getLmsCompleteness:" + result);
        return JSON.parseObject(result, LmsCompleteness.class);
    }


    public static Courseware getUserCourseInfo(WebDriver driver, Long courseId, int page, int pageSize) throws Exception {


        String cookie = Util.getCookie(driver.manage().getCookies());

//        int page = 1;
//        int pageSize=20;
        String getUrl = "https://lms.ouchn.cn/api/course/" + courseId + "/coursewares?conditions=%7B%22category%22:null,%22itemsSortBy%22:%7B%22predicate%22:%22chapter%22,%22reverse%22:false%7D,%22ignore_activity_types%22:%5B%22lesson%22%5D%7D" +
                "&page=" + page + "&page_size=" + pageSize;

        Map<String, String> heads = Maps.newHashMap();
        heads.put("referer", "https://lms.ouchn.cn/course/" + courseId + "/ng");
        heads.put(":method", "GET");
        heads.put(":authority", "lms.ouchn.cn");
        heads.put("cookie", cookie);
        //     heads.put(":path", "/api/course/" + courseId + "/activity-reads-for-user");
        heads.put("accept", "application/json, text/plain, */*");

        String result = HttpUtil.getLmsOuchn(getUrl, cookie, heads);
        System.err.println("result:::" + result);
        return JSON.parseObject(result, Courseware.class);
    }


    private static List<WebElement> findWeElements(WebDriver driver, String cssSelector, int second) {
        return (new WebDriverWait(driver, Duration.ofSeconds(second))).until((ExpectedCondition<List<WebElement>>)
                d -> {
                    assert d != null;
                    return d.findElements(By.cssSelector(cssSelector));
                });
    }

    public static List<WebElement> findElementsByCssSelector(WebDriver driver, String cssSelector, long seconds) {
        return (new WebDriverWait(driver, Duration.ofSeconds(seconds)).until((ExpectedCondition<List<WebElement>>)
                d -> {
                    assert d != null;
                    return d.findElements(By.cssSelector(cssSelector));
                }));
    }

    public static WebElement findElementByCssSelector(WebDriver driver, String cssSelector, long seconds) {
        return (new WebDriverWait(driver, Duration.ofSeconds(seconds)).until((ExpectedCondition<WebElement>)
                d -> {
                    assert d != null;
                    return d.findElement(By.cssSelector(cssSelector));
                }));
    }


    //   String js = "document.getElementByClassName(\"mvp-play-progress\").setAttribute(\"style\",\"width: 97.5%;\")";
//        String js = "$('.mvp-play-progress').css('style','width: 20.5%;') ";
//
//        ((JavascriptExecutor) driver).executeScript(js);

    // https://www.cnblogs.com/du-hong/p/15337826.html
//        Thread.sleep(2000);
//        Actions action = new Actions(driver);
//     //   WebElement target = driver.findElement(By.className("mvp-play-progress"));
//      //  WebElement target = findElementByCssSelector(driver,"div[class='mvp-play-progress']",20);
//        WebElement target = findElementByCssSelector(driver,"div[class='mvp-progress-control']",20);
//     //   action.dragAndDropBy(target,1000,0);
//       // action.contextClick(target).moveByOffset(990,0).perform();
//
//     System.err.println("x:"+   target.getLocation().x);
//     System.err.println("y:"+   target.getLocation().y);
//
//     WebElement t1 = driver.findElement(By.cssSelector("button[class='mvp-play-rate-btn']"));
//        System.err.println("t1x:"+   t1.getLocation().x);
//        System.err.println("t1y:"+   t1.getLocation().y);
//
//        action.contextClick(target).moveToElement(t1).perform();
//
//        Thread.sleep(2000000);

}
